﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.Practices.Unity;

namespace CMS.Web.Engine
{
    public enum LifetimeManagement
    {
        ContainerControlled,
        PerThread,
        ExternallyControlled
    }
    
    public class IoCContainer
    {      
        private UnityContainer _container;
        private static IoCContainer _current;

        private IoCContainer() 
        {
            _container = new UnityContainer();
        }

        public static IoCContainer Current
        {
            get
            {
                if (_current.IsNull())
                    _current = new IoCContainer();
                return _current;
            }
        }
        public void RegisterType<TFrom, TTo>()
        {
            _container.RegisterType(typeof(TFrom), typeof(TTo)); 
        }

        public void RegisterType<TFrom, TTo>(LifetimeManagement lifetime)
        {            
            LifetimeManager manager = null;

            if (lifetime == LifetimeManagement.ContainerControlled)
                manager = new ContainerControlledLifetimeManager();

            else if (lifetime == LifetimeManagement.PerThread)
                manager = new PerThreadLifetimeManager();

            else if (lifetime == LifetimeManagement.ExternallyControlled)
                manager = new ExternallyControlledLifetimeManager();

            _container.RegisterType(typeof(TFrom), typeof(TTo), manager);
            
            //_container.RegisterType(typeof(string), new InjectionConstructor(

        }

        public T Resolve<T>()
        {           
            return (T)_container.Resolve(typeof(T));
        }

        public object Resolve(Type type)
        {
            return _container.Resolve(type); 
        }
    }
}